<template>
  <div class="app-container">
    <el-form ref="roleForm" :model="role" :rules="rules" label-width="100px">
      <el-row>
        <el-col :xs="18" :sm="18" :md="18" :lg="24">
          <el-form-item>
            <div style="float:right;">
              <el-button @click="saveRole('roleForm')">
                <icon-svg icon-class="baocun1"></icon-svg>&nbsp;&nbsp;保存</el-button>
              <el-button @click="cancel">
                <icon-svg icon-class="quxiao"></icon-svg>&nbsp;&nbsp;取消</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="18" :sm="18" :md="18" :lg="6">
          <el-form-item label="角色名称" prop="rolename">
            <el-input v-model="role.rolename" :maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="18" :sm="18" :md="18" :lg="6">
          <el-form-item label="角色平台" prop="platform">
            <el-select v-model="role.platform" placeholder="请选择活动区域" :disabled="true">
              <el-option label="后台" value="ROLE_ADMIN"></el-option>
              <!-- <el-option label="前台" value="ROLE_FRONT"></el-option> -->
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="功能权限">
          <div v-for="(fun,index0) in funcBtnList" :key="fun.permissionid" :value="fun.permissionid" v-if="fun.typecode === 'NAVIGATE' &&  fun.rootid === 0" class="funNavi">
            <!-- <div class="menu">{{fun.permissionname}}</div> -->
            <el-checkbox v-model="fun.isCheck" :name="fun.permissionid+''" @change="handlerChange">{{fun.permissionname}}</el-checkbox>
            <div v-for="(childfun,index1) in funcBtnList" :key="childfun.permissionid" :value="childfun.permissionid" v-if="(childfun.rootid === fun.permissionid && childfun.typecode === 'NAVIGATE' && childfun.typecode !== 'FUNCTION')" class="funcbtn">
              <!-- <span class="menu">{{childfun.permissionname}}</span> -->
              <el-checkbox v-model="childfun.isCheck" :name="childfun.permissionid+''" @change="handlerChange">{{childfun.permissionname}}</el-checkbox>
              <span v-for="(threeChildfunBtn,index2) in funcBtnList" :key="threeChildfunBtn.permissionid" :value="threeChildfunBtn.permissionid" v-if="threeChildfunBtn.rootid === childfun.permissionid && threeChildfunBtn.typecode === 'FUNCTION'" class="funcbtn">
                <el-checkbox v-model="threeChildfunBtn.isCheck" :name="threeChildfunBtn.permissionid+''" @change="handlerChange">{{threeChildfunBtn.permissionname}}</el-checkbox>
              </span>
            </div>
            <span v-for="(childfun,index3) in funcBtnList" :key="childfun.permissionid" :value="childfun.permissionid" v-if="(childfun.rootid === fun.permissionid && childfun.typecode === 'FUNCTION')" class="funcbtn">
              <el-checkbox v-model="childfun.isCheck" :name="childfun.permissionid+''" @change="handlerChange">{{childfun.permissionname}}</el-checkbox>
              <span v-for="(threeChildfun,index4) in funcBtnList" :key="threeChildfun.permissionid" :value="threeChildfun.permissionid" v-if="threeChildfun.rootid === childfun.permissionid && threeChildfun.typecode === 'FUNCTION'" class="funcbtn">
                <el-checkbox v-model="threeChildfun.isCheck" :name="threeChildfunBtn.permissionid+''" @change="handlerChange">{{threeChildfun.permissionname}}</el-checkbox>
              </span>
            </span>
          </div>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<style scoped>
.pagination {
  text-align: center;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.colSpace {
  margin-left: 5px;
}

.tips {
  font-size: 14px;
  color: red;
}

.viewBtn {
  float: right;
}

.selectStyle {
  width: 340px;
}

.funcbtn {
  margin-left: 10px;
}

.funNavi {
  margin-left: 0px;
  border: 1px dashed #d1dbe5;
}

.menu {
  color: #1f2d3d;
  font-weight: 100;
}

.el-checkbox {
  font-weight: 100;
}
</style>

<script>
import { getRole, saveRoleEdit, queryPermission } from 'api/system';
import { parseTime } from 'utils/index';
import { strParseInt } from 'utils/customer';

export default {
  data() {
    return {
      role: {
        roleid: null,
        rolename: null,
        platform: null,
        rolePermission: []
      },
      rules: {
        rolename: [{ required: true, message: '请输入角色名称', trigger: 'blur' },
        { max: 50, message: '长度最大为50字符', trigger: 'blur' }],
      },
      listLoading: true,
      funcBtnList: [],
      currentPrivList: [],
      isAll: false
    }
  },
  watch: {
    'role.platform': {
      handler(newValue, oldValue) {
        this.isHidden = true
      }
    }
  },
  created() {
    this.role = this.$route.query.role;
    this.fetchData();
  },
  methods: {
    // 获取角色功能配置项
    fetchData() {
      let requestParams = {
        roleid: this.role.roleid || ''
      }
      queryPermission(requestParams).then(response => {
        let res = response.data;
        this.funcBtnList = [];
        if (res.flag === 1) {
          let funList = res.data;
          for (let i = 0; i < funList.length; i++) {
            let fobj = {
              permissionid: '',
              permissionname: '',
              rootid: '',
              typecode: '',
              isCheck: false
            }
            fobj.permissionid = funList[i]['permissionid'];
            fobj.permissionname = funList[i]['permissionname'];
            fobj.rootid = funList[i]['rootid'];
            fobj.typecode = funList[i]['typecode'];
            fobj.isCheck = funList[i]['isCheck'];
            this.funcBtnList.push(fobj);
          }
        }
      });
    },
    saveRole(roleForm) {
      this.getCurrentConfigPriv();
      this.checkIsBtnAll();
      if (this.isAll) {
        this.$message({
          showClose: true,
          message: '角色不能拥有所有权限',
          type: 'error'
        });
        return
      }
      this.$refs['roleForm'].validate(valid => {
        if (valid) {
          saveRoleEdit(this.role).then(response => {
            let res = response.data;
            this.listLoading = true;
            if (res.flag == 1) {
              this.$message({
                showClose: true,
                message: '权限配置编辑成功',
                type: 'success'
              });
              this.$router.go(-1);
            } else {
              this.$message({
                showClose: true,
                message: '权限配置编辑失败',
                type: 'error'
              });
            }
            this.listLoading = false
          });
        }
      });
    },
    cancel() {
      this.$router.go(-1);
    },
    // 获取当前功能权限配置项
    getCurrentConfigPriv() {
      this.currentPrivList = [];
      // for (let i = 0; i < this.funcBtnList.length; i++) {
      //   if (this.funcBtnList[i].isCheck) {
      //      this.setParentCheck(this.funcBtnList,this.funcBtnList[i],true)    
      //   }    
      // };
      // _.uniq(this.currentPrivList);
      for (let i = 0; i < this.funcBtnList.length; i++) {
        if (this.funcBtnList[i].isCheck) {
          this.currentPrivList.push(this.funcBtnList[i].permissionid);
        }
      };
      this.role.rolePermission = this.currentPrivList.join(',');
    },
    // 判断功能权限是否全部选中
    checkIsBtnAll() {
      this.isAll =  this.currentPrivList.length === this.funcBtnList.length
    },
    // 处理选中事件
    handlerChange(event) {
      // 根据所选状态设定父节点状态
      for (let i = 0; i < this.funcBtnList.length; i++) {
        // 查找选中节点对象
        if ((this.funcBtnList[i].permissionid + '') === event.target.name) {
          // 设置节点状态
          this.funcBtnList[i].isCheck = event.target.checked
          if (event.target.checked) {
            this.setParentCheck(this.funcBtnList, this.funcBtnList[i], event.target.checked);
          }
          this.setChildCheck(this.funcBtnList, this.funcBtnList[i], event.target.checked); 
        }
      }
    },
    // 设置上级节点选中状态
    setParentCheck(funcList, currentFunc, checked) {
      const parentBtnList = funcList.filter(fun => {
        return fun.permissionid === currentFunc.rootid
      })
      for (let i = 0; i < parentBtnList.length; i++) {
        parentBtnList[i].isCheck = checked
        this.setParentCheck(funcList, parentBtnList[i], checked)
      }
    },
    // 设置下属节点选中状态
    setChildCheck(funcList, currentFunc, checked) {
      // console.log(currentFunc.permissionid)
      const childBtnList = funcList.filter(fun => {
        return fun.rootid === currentFunc.permissionid
      })
      for (let i = 0; i < childBtnList.length; i++) {
        childBtnList[i].isCheck = checked
        this.setChildCheck(funcList, childBtnList[i], checked)
      }
    }
  }
};
</script>